package com.hhf.rpa.file.controller;

import com.hhf.rpa.base.ResponseResult;
import com.hhf.rpa.file.config.FileConfig;
import com.hhf.rpa.file.model.BaseFile;
import com.hhf.rpa.file.service.BaseFileService;
import com.hhf.rpa.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileConfig fileConfig;
    @Autowired
    private BaseFileService baseFileService;

    @PostMapping("/upload")
    public ResponseResult<BaseFile> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.failure("1001","上传失败，文件不存在");
        }
        try {
            // 获取绝对路径
            String storagePath = fileConfig.getStoragePath();
            String fileName = file.getOriginalFilename();
            Path path = Paths.get(storagePath, fileName);
            FileUtils.createDirectoriesRecursively(storagePath);
            if (Files.exists(path) || baseFileService.isExists(fileName)) {
                return ResponseResult.failure("1002","上传失败: 文件名"+fileName+"或文件重复");
            } else {
                // 将文件写入指定路径
                Files.copy(file.getInputStream(), path);
                // 记录上传文件
                BaseFile baseFile = baseFileService.saveFile(file, fileConfig);
                return ResponseResult.success(baseFile);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return ResponseResult.failure("1003","上传失败:"+ e.getMessage());
        }
    }
}
